/**
 * @Description : 上传模块
 **/
const userModel = require("../model/userModel");
const userFileModel = require("../model/userFileModel");
const { output } = require("../common/index");
const moment = require("moment");
const fs = require("fs");
const path = require("path");
const sharp = require("sharp");

const upload = async (req, res, next) => {
    try {
        let tmpRequest = req.body && req.body.params ? JSON.parse(req.body.params) : req.query ? req.query : "";
        console.log("upload tmpRequest", tmpRequest);

        if (req.files === null) {
            output(res, { code: 2, msg: "请上传文件" });
        } else {
            if (tmpRequest.account && tmpRequest.type_id) {
                let tmpTypeID = tmpRequest.type_id;
                let tmpFolderName = tmpRequest.folder_name;

                //判断文件夹是否存在,不存在则创建 process.env.UPLOAD_DIR + tmpPath
                let tmpPath = "user/" + tmpRequest.account + "/" + moment().format("YYYYMM") + "/";
                func_checkFolder(process.env.UPLOAD_DIR + tmpPath);

                let file = req.files.file;
                //判断文件大小
                if (file.size > process.env.UPLOAD_LIMIT) {
                    output(res, {
                        code: 2,
                        msg: "上传文件容量超过 " + Math.floor(process.env.UPLOAD_LIMIT / 1024) + "K，请重新上传",
                        data: {}
                    });
                } else {
                    let tmpRandom = moment().format("X") + Math.floor(Math.random() * 899 + 100);
                    let tmpFileType = path.extname(file.name).substring(1).toLowerCase();
                    let tmpFileName = tmpRandom + "." + tmpFileType;
                    let tmpPathFile = process.env.UPLOAD_DIR + tmpPath + tmpFileName;

                    console.log("tmpPathFile", tmpPathFile);

                    file.mv(tmpPathFile, async (err) => {
                        if (err) {
                            output(res, {
                                code: 2,
                                msg: "上传文件失败",
                                data: {}
                            });
                        } else {
                            let formArrOp = {};
                            formArrOp["account"] = tmpRequest.account;
                            formArrOp["folder_id"] = tmpTypeID;
                            formArrOp["folder_name"] = tmpFolderName;
                            formArrOp["file_name"] = tmpFileName;
                            formArrOp["file_old_name"] = file.name.toString("utf8");
                            formArrOp["file_url"] = tmpPath + tmpFileName;
                            formArrOp["file_size"] = file.size;
                            formArrOp["file_type"] = 2;
                            formArrOp["file_suffix"] = tmpFileType;
                            formArrOp["status"] = 1;
                            formArrOp["create_user"] = tmpRequest.account;
                            formArrOp["create_time"] = Math.floor(Date.now() / 1000);

                            if (
                                tmpFileType == "jpg" ||
                                tmpFileType == "jpeg" ||
                                tmpFileType == "png" ||
                                tmpFileType == "gif"
                            ) {
                                let imageSize = require("image-size");
                                let dimensions = imageSize(tmpPathFile);
                                formArrOp["file_type"] = 1;
                                formArrOp["file_width"] = dimensions.width;
                                formArrOp["file_height"] = dimensions.height;

                                if (dimensions.width > 1000) {
                                    let tmpFileName2 = tmpRandom + "_2." + tmpFileType;
                                    await sharp(tmpPathFile)
                                        .resize({ width: 1000 })
                                        .jpeg({ quality: 50 })
                                        .toFile(process.env.UPLOAD_DIR + tmpPath + tmpFileName2, (err, info) => {
                                            formArrOp["file_url_compress"] = tmpPath + tmpFileName2;
                                            formArrOp["file_compress_width"] = info.width;
                                            formArrOp["file_compress_height"] = info.height;
                                        });
                                }
                            }

                            await userFileModel
                                .create(formArrOp)
                                .then((result) => {
                                    console.log("file result", result);
                                    output(res, { code: 1, msg: "上传文件成功", data: { url: result.id } });
                                })
                                .catch((err) => {
                                    output(res, { code: 2, msg: "上传失败" + JSON.stringify(err) });
                                });
                        }
                    });
                }
            } else {
                output(res, { code: 2, msg: "非法用户", data: {} });
            }
        }
    } catch (error) {
        output(res, { code: 2, msg: "操作错误" + error });
    }
};

//判断文件夹是否存在,不存在则创建
const func_checkFolder = (folderPath) => {
    const dirPath = path.join(folderPath);
    fs.access(dirPath, fs.constants.F_OK, (err) => {
        if (err) {
            fs.mkdir(dirPath, { recursive: true }, (mkdirErr) => {
                if (mkdirErr) {
                    return { code: 2, msg: "创建文件夹失败" + mkdirErr };
                } else {
                    return { code: 1, msg: "创建文件夹成功" };
                }
            });
        } else {
            return { code: 2, msg: "文件夹已存在" };
        }
    });
};

module.exports = { upload };
